﻿
namespace SharePointListService.SADev.SharePoint
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.XPath;

    public static class SharePointHelpers
    {
        public static void AddNewItemsToBatch(this XContainer batch, Dictionary<string, object> fields)
        {
            const string Id = "New";

            var methodElement = new XElement("Method",
                            new XAttribute("ID", batch.Descendants().Count() + 1),
                            new XAttribute("Cmd", "New"),
                            new XElement("Field",
                                new XAttribute("Name", "ID"),
                                Id));

            if (fields != null)
            {
                if (fields.Count == 0)
                {
                    return;
                }

                foreach (KeyValuePair<string, object> field in fields)
                {
                    methodElement.Add(new XElement("Field",
                        new XAttribute("Name", field.Key),
                        field.Value));
                }
            }

            batch.Add(methodElement);
        }

        public static XElement CreateBatch(string viewId)
        {
            return new XElement("Batch",
                new XAttribute("OnError", "Continue"),
                new XAttribute("ListVersion", 1),
                new XAttribute("ViewName", viewId));
        }

        public static string ToSharePointDateTimeFormat(this DateTime datetime)
        {
            return datetime.ToString("yyyy-MM-ddTHH:mm:ssZ");
        }

        public static void Insert(this XElement batch, Lists sharePointList, string listId)
        {
            if (batch.DescendantNodes().Count() > 0)
            {
                XmlNode resultsNode;
                try
                {
                    resultsNode = sharePointList.UpdateListItems(listId, (XmlNode)batch.ToXPathNavigable());
                }                
                catch (System.Web.Services.Protocols.SoapException err)
                {
                    if (err.Message.Contains("Microsoft.SharePoint.SoapServer.SoapServerException"))
                    {
                        throw new Exception(err.Detail.InnerText, err);
                    }

                    throw;
                }

                XmlNamespaceManager sharePointNameSpace = new XmlNamespaceManager(resultsNode.OwnerDocument.NameTable);
                sharePointNameSpace.AddNamespace("s", resultsNode.NamespaceURI);
                string errorCode = resultsNode.SelectSingleNode("//s:ErrorCode", sharePointNameSpace).InnerText;
                if (errorCode != "0x00000000")
                {
                    var errorMessage = resultsNode.SelectSingleNode("//s:ErrorText", sharePointNameSpace).InnerText;
                    throw new Exception(string.Format(CultureInfo.CurrentCulture, "Error inserting to SharePoint. Message: {1}{0}" +
                        "Code: {2}{0}" +
                        "Batch XML: {3}", Environment.NewLine, errorMessage, errorCode, batch));
                }
            }
        }

        public static IXPathNavigable ToXPathNavigable(this XNode element)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(element.ToString(SaveOptions.DisableFormatting));
            return doc.FirstChild;
        }
    }
}
